package com.hcr.elecident;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.FaceSDKManager;
import com.google.gson.Gson;
import com.hcr.SSLSocketClient;
import com.hcr.entity.Device;
import com.hcr.entity.User;
import com.hcr.util.MacAddressManager;
import com.hcr.util.MyConst;
import com.hcr.util.Result;

import java.io.IOException;
import java.net.NetworkInterface;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.bfy.dualsim.TelephonyManagement;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.hcr.elecident.WelcomeActivity.TEMP_DATA;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    private TelephonyManagement.TelephonyInfo telephonyInfo;

    public static final MediaType JSONTO = MediaType.parse("application/json;charset=utf-8");

    static final String[] PERMISSION = new String[]{
            //获取照相机权限
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityManager.getActivityManager().pushActivity(this);

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //Android 6.0申请权限
            ActivityCompat.requestPermissions(this, PERMISSION, 1);
        }

        webView = (WebView) findViewById(R.id.myweb);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 增加localstore支持
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);

        // 支持下载
        webView.setDownloadListener(new MyDownload());

        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        // 允许访问url
        webSettings.setAllowFileAccessFromFileURLs(true);

        webView.addJavascriptInterface(this, "nativeMethod");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });


        webView.loadUrl("file:///android_asset/1.html");
    }

    /**
     * 上传跳转
     */

    @JavascriptInterface
    public void uploadMsg() {
        com.hcr.elecident.ActivityManager.getActivityManager().popActivity(this);
    }


    /**
     * 退出到未登录状态
     */
    @JavascriptInterface
    public void backLogin() {
        // 清楚数据
        SharedPreferences preferences = getSharedPreferences(TEMP_DATA, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.commit();

        clearGoTo();

    }

    public void clearGoTo() {
        final Intent it = new Intent(this, MainActivity.class);
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                startActivity(it);
                finish();
            }
        };
        timer.schedule(task, 100 * 1);
    }

    @JavascriptInterface
    public void togo6() {

        Intent intent = new Intent(this, PageActivity.class);

        SharedPreferences pre = getSharedPreferences(TEMP_DATA, MODE_PRIVATE);
        String id = pre.getString("id", null);
        String idNumber = pre.getString("idNumber", null);
        String photo = pre.getString("photo", null);
        String name = pre.getString("name", null);
        String pass = pre.getString("pass", "n");
        intent.putExtra("id", id);
        intent.putExtra("num", idNumber);
        intent.putExtra("fileName", photo);
        intent.putExtra("name", name);
        intent.putExtra("pass", pass);

        System.out.println("跳转数据："+"id:"+id+",idnumber:"+idNumber+",name:"+name+",photo:"+photo);
        startActivity(intent);

        finish();
    }

    @JavascriptInterface
    public void camera(String name, String num, String id) {
        System.out.println("认证之前传递的参数："+name+","+num+","+id);
        requestPermissions(99, Manifest.permission.CAMERA);

        init();
        Intent it = new Intent(MainActivity.this, FaceDetectActivity.class);
        it.putExtra("name", name);
        it.putExtra("num", num);
        it.putExtra("id", id);
        startActivity(it);
    }
    private void init() {
        // 如果图片中的人脸小于200*200个像素，将不能检测出人脸，可以根据需求在100-400间调节大小
        FaceSDKManager.getInstance().getFaceTracker(this).set_min_face_size(200);
        FaceSDKManager.getInstance().getFaceTracker(this).set_isCheckQuality(true);
        // 该角度为商学，左右，偏头的角度的阀值，大于将无法检测出人脸，为了在1：n的时候分数高，注册尽量使用比较正的人脸，可自行条件角度
        FaceSDKManager.getInstance().getFaceTracker(this).set_eulur_angle_thr(45, 45, 45);
        FaceSDKManager.getInstance().getFaceTracker(this).set_isVerifyLive(true);
    }

//    @JavascriptInterface
//    public void shareData(String phone) {
//
//        // 判断是否有数据
//        SharedPreferences pre = getSharedPreferences(WelcomeActivity.TEMP_DATA,MODE_PRIVATE);
//        String info = pre.getString(phone,null);  //姓名
//        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+ info);
//        if (info != null){
//            String infos[] = info.split("@");
//            final Intent it = new Intent(this, PageActivity.class);
//            it.putExtra("name",infos[0]);
//            it.putExtra("num",infos[1]);
//            it.putExtra("fileName",infos[2]);
//            startActivity(it);
//        }
//    }


    private Map<String, String> show() {
        try {
            telephonyInfo = TelephonyManagement.getInstance().updateTelephonyInfo(this).getTelephonyInfo(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imeiSIM1 = telephonyInfo.getImeiSIM1();
        String imeiSIM2 = telephonyInfo.getImeiSIM2();

        String imsiSIM1 = telephonyInfo.getImsiSIM1();
        String imsiSIM2 = telephonyInfo.getImsiSIM2();

        String macid = MacAddressManager.getAdresseMAC(getApplicationContext());
        String brand = Build.BRAND;  // 品牌
        String android = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        String model = Build.MODEL;

//        System.out.println(" IMEI1 : " + imeiSIM1 + "\n" +
//                " IMEI2 : " + imeiSIM2 + "\n" +
//                " IMSI1 : " + imsiSIM1 + "\n" +
//                " IMSI2 : " + imsiSIM2 + "\n");

        Map<String, String> map = new HashMap<>();
        map.put("imei1", imeiSIM1);
        map.put("imei2", imeiSIM2);
        map.put("imsi1", imsiSIM1);
        map.put("imsi2", imsiSIM2);

        map.put("macid", macid);
        map.put("androidid", android);
        map.put("deviceinfo", brand + " " + model);

        return map;
    }
    /**
     * 手机号变更
     * @param id
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @JavascriptInterface
    public int updatePhone(String id,String phone,String password,String code) throws Exception {
//        System.out.println("phone:"+phone+",password:"+password);

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("id",id)
                .add("phone",phone)
                .add("password",password)
                .build();
        Request request = new Request.Builder()
                .url(new URL(MyConst.HT+"user/updatePhone"))
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        String responseData = response.body().string();

        Result result = JSON.parseObject(responseData,new Result<User>().getClass());
        if (result.getCode().equals(200)){
            return 1;
        }else if (result.getCode().equals(400)){
            return -1;
        }else if (result.getCode().equals(401)){
            return -2;
        }else if (result.getCode().equals(404)){
            return -3;
        }
        return -100;
    }
    @JavascriptInterface
    public int reg(String phone, String password) throws Exception {
        Map<String, String> res = new HashMap<>();
        if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
        } else {
            res = show();
        }

//        System.out.println("phone:" + phone + ",password:" + password);
        postDevice();
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("phone", phone)
                .add("password", password)

                .add("macid", res.get("macid"))
                .add("androidid", res.get("androidid"))
                .add("imei1", res.get("imei1"))
                .add("imei2", res.get("imei2"))
                .add("imsi1", res.get("imsi1"))
                .add("imsi2", res.get("imsi2"))
                .add("deviceinfo", res.get("deviceinfo"))
                .build();
        Request request = new Request.Builder()
                .url(new URL(MyConst.HT + "user/reg"))
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        String responseData = response.body().string();

        Result result = JSON.parseObject(responseData, new Result<User>().getClass());

//        System.out.println("返回数据：" + result.toString());
        if (result.getCode() == 401) {
            return 401;
        } else if (result.getCode() == 200) {
            // 收集收集信息
            return 200;
        } else if (result.getCode() == 400) {
            return 400;
        }
        return 400;
    }

    @JavascriptInterface
    public int setPwd(String phone, String password) throws Exception {
//        System.out.println("phone:" + phone + ",password:" + password);

        try{
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("phone", phone)
                    .add("password", password)
                    .build();
            Request request = new Request.Builder()
                    .url(new URL(MyConst.HT + "user/resetPwd"))
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();

            Result result = JSON.parseObject(responseData, new Result<User>().getClass());
            if (200 == result.getCode()) {
                return 1;
            } else if (400 == result.getCode()) {
                return 2;
            } else if (401 == result.getCode()) {
                return 3;
            }
        } catch (Exception e){
            return 0;
        }
        return 0;
    }


    public void postDevice() {
        OkHttpClient okHttpClient = new OkHttpClient();
//        System.out.println(getDevice());
        String json = getDevice();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(MyConst.HT + "device/save")//请求的url
                .post(requestBody)
                .build();
        okhttp3.Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                final String res = response.body().string();
                if (response.code() == 200) {
//                    System.out.println("======================ok==============================");
                }
            }
        });
    }


    @JavascriptInterface
    public String isLogin(String phone, String password) throws Exception {
//        System.out.println(getLngAndLat(getApplicationContext()));

        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("phone", phone)
                    .add("password", password)
                    .build();
            Request request = new Request.Builder()
                    .url(new URL(MyConst.HT + "user/login"))
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();


            Result result = JSON.parseObject(responseData, new Result<User>().getClass());
            // 写入数据到本地
            SharedPreferences.Editor editor = getSharedPreferences(TEMP_DATA, MODE_PRIVATE).edit();
            if (result.getMsg().equals("ok")) {
                JSONObject jsonObject = JSON.parseObject(result.getData().toString());
                String id = jsonObject.get("id").toString();
                // 登录成功
                System.out.println("登陆成功之后获取的用户编号："+id);
                if (result.getData() == null) {
                    // 没有验证过，需要去验证
                    return "ok-no-" + id;
                } else {

                    if (jsonObject.get("status").toString().equals("0")) {
                        // 没认证
                        editor.putString("isRZ", "0");
                        editor.putString("pass", "n");
                        return "ok-no-" + id;
                    } else {


                        // 认证通过
                        editor.putString("pass", "y");

                        // 传给前台准备显示数据
                        String name = jsonObject.get("name").toString();
                        String idNumber = jsonObject.get("idNumber").toString();
                        String address = jsonObject.get("address").toString();
                        String sex = jsonObject.get("sex").toString();
                        String photo = jsonObject.get("photo").toString();

                        editor.putString("isRZ", "1");
                        // 写入数据到本地
                        editor.putString("id", id);
                        editor.putString("name", name);
                        editor.putString("idNumber", idNumber);
                        editor.putString("address", address);
                        editor.putString("sex", sex);
                        editor.putString("photo", photo);
                        editor.commit();
                        return "ok-yes-" + id;
                    }
                }
            } else {
                // 登录失败
                return "no-no";
            }
        } catch (Exception e) {
            return "x-x";
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public void over() {
//        finish();
//        finish();
        ActivityManager.getActivityManager().popAllActivity();
        System.exit(0);//正常退出
    }

//    ############

    public void requestPermissions(int requestCode, String permission) {
        if (permission != null && permission.length() > 0) {
            try {
                if (Build.VERSION.SDK_INT >= 23) {
                    // 检查是否有权限
                    int hasPer = checkSelfPermission(permission);
                    if (hasPer != PackageManager.PERMISSION_GRANTED) {
                        // 是否应该显示权限请求
                        boolean isShould = shouldShowRequestPermissionRationale(permission);
                        requestPermissions(new String[]{permission}, requestCode);
                    }
                } else {

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                show();
            } else {
                Toast.makeText(MainActivity.this, "用户拒绝授权！", Toast.LENGTH_SHORT).show();
            }
        }


        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
        if (!flag) {
            requestPermissions(99, Manifest.permission.CAMERA);
        }
    }

    //    sendHttp
    public void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody body = new FormBody.Builder()
                            .add("", "")
                            .build();
                    Request request = new Request.Builder()
                            .url(new URL(""))
                            .post(body)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static boolean isPase(String name, String idnumber, String image) {


        try {

            OkHttpClient mHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())//配置
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置
                    .build();

            HashMap<String, Object> map = new HashMap<>();
            map.put("cmd", "faceRecognition");
            map.put("name", name);
            map.put("idnumber", idnumber);
            map.put("image", image);
            map.put("imagetype", 0);
            map.put("sendTime", Long.toString(System.currentTimeMillis()));
            map.put("terminalNo", System.currentTimeMillis()+"");


//            System.out.println("发送请求前Name" + name);


            Gson gson = new Gson();
            String data1 = gson.toJson(map);


//            System.out.println("发送请求前Name" + gson.fromJson(data1, Map.class).get("name"));

//            OkHttpClient client = new OkHttpClient();
//            RequestBody body = new FormBody.Builder()
//                    .add("cmd","faceRecognition")
//                    .add("name",name)
//                    .add("idnumber",idnumber)
//                    .add("image",image)
//                    .add("imagetype","0")
//                    .add("sendTime",Long.toString(System.currentTimeMillis()))
//                    .add("terminalNo",UUID.randomUUID().toString())
//                    .build();
            RequestBody body = RequestBody.create(JSONTO, data1);
            Request request = new Request.Builder()
                    .url(new URL(MyConst.FACE))
                    .post(body)
//                    .addHeader("Connection", "close")
                    .build();
            Response response = mHttpClient.newCall(request).execute();
            String responseData = response.body().string();

//            System.out.println(":" + responseData + "@");
            return isFacePase(parseJsonToInfoBean(responseData));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static InfoBean parseJsonToInfoBean(String str) {
        InfoBean infoBean = new InfoBean();
        Gson gson = new Gson();
        infoBean = gson.fromJson(str, InfoBean.class);
        return infoBean;
    }

    public static boolean isFacePase(InfoBean infoBean) {
        if (infoBean == null) {
            return false;
        }
        if (infoBean.getResponseCode() == 100) {
            if (infoBean.getResult().equals("1")) {
                return true;
            } else {
                return false;
            }
        } else if (infoBean.getResponseCode() == 420) {
            return false;
        } else {
            return false;
        }
    }

//    --------------证书

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }


    private static class TrustAllCerts implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    class MyDownload implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            //检测是下载apk
            if (url.endsWith(".apk")) {
                //通过uri与Intent来调用系统通知，查看进度
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                new DownloadThread(url).start();
            }
        }
    }

    ///////

    /**
     * 获取经纬度
     *
     * @param context
     * @return
     */
    public String getLngAndLat(Context context) {
        double latitude = 0.0;
        double longitude = 0.0;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            } else {//当GPS信号弱没获取到位置的时候又从网络获取
                return getLngAndLatWithNetwork();
            }
        } else {    //从网络获取经纬度
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }
        return longitude + "," + latitude;
    }

    //从网络获取经纬度
    public String getLngAndLatWithNetwork() {
        double latitude = 0.0;
        double longitude = 0.0;
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
        return longitude + "," + latitude;
    }


    LocationListener locationListener = new LocationListener() {

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {

        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
        }
    };

//    public static String getDeviceInfo(Context context) {
//        try{
//            org.json.JSONObject json = new org.json.JSONObject();
//
//            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//
//            String mac = wifi.getConnectionInfo().getMacAddress();
//            json.put("mac", mac);
//
//
//            return json.toString();
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }

    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }

    public String getDevice() {
        String macid = MacAddressManager.getAdresseMAC(getApplicationContext());
        String brand = Build.BRAND;  // 品牌
        String android = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        String model = Build.MODEL;
        String os = Build.VERSION.RELEASE;

        Device device = new Device(brand, model, android, os, macid);
        String s = JSON.toJSONString(device);
        return s;
    }


}

